import React, { useEffect, useState } from "react";
import Navbar from "../../../compounts/navber/Navbar";
import request from "../../../api/request";
import { Avatar, List, Space, Button, Input, TextArea, Toast, Popup, Picker, DatePickerView } from "antd-mobile";
import { FillinOutline, EyeFill, AddOutline, CloseOutline } from "antd-mobile-icons";
import style from "./circle.module.css";
import { useNavigate } from "react-router-dom";

function Index() {
    const navigate = useNavigate();
    // 列表数据
    const [list, setList] = useState([]);
    const [listDeptId, setListDeptId] = useState(1);
    // 发表弹层
    const [showPublish, setShowPublish] = useState(false);
    const [form, setForm] = useState({
        title: "",
        departmentId: "",
        departmentName: "",
        disease: "",
        detail: "",
        treatmentHospital: "",
        treatmentStartTime: "",
        treatmentEndTime: "",
        treatmentProcess: "",
        amount: 10,
    });

    // 科室/病症选项 & 控件可见性
    const [departments, setDepartments] = useState([]);
    const [showStartPicker, setShowStartPicker] = useState(false);
    const [showEndPicker, setShowEndPicker] = useState(false);
    const [startTempDate, setStartTempDate] = useState(new Date());
    const [endTempDate, setEndTempDate] = useState(new Date());
    // 内部选择面板
    const [selectorMode, setSelectorMode] = useState("none"); // 'dept' | 'disease' | 'none'
    const [selectorQuery, setSelectorQuery] = useState("");
    const parseDateFromString = (str) => {
        try {
            const [y, m, d] = (str || '').split('-').map((n) => Number(n));
            if (y && m && d) return new Date(y, m - 1, d);
        } catch {
            // 忽略日期解析错误
        }
        return new Date();
    };



    // 按科室名称联动病症（可替换为接口返回的真实映射）
    // 疾病列表缓存：{ [departmentId]: Array<{label,value}> }
    const [diseaseMap, setDiseaseMap] = useState({});

    const fetchDiseasesByDepartment = async (deptId) => {
        if (!deptId) return;
        // 如果已有缓存，跳过
        if (diseaseMap[String(deptId)]) return;
        try {
            const res = await request.get('/share/knowledgeBase/v1/findDiseaseCategory', { params: { departmentId: Number(deptId) } });
            const arr = (res?.data?.result || []).map((it) => ({ label: it.name, value: String(it.id) }));
            setDiseaseMap((m) => ({ ...m, [String(deptId)]: arr }));
        } catch (e) {
            console.error(e);
        }
    };

    // 请求列表数据
    const fetchList = (deptIdParam) => {
        const deptId = Number(deptIdParam || listDeptId || 1);
        request.get("/user/sickCircle/v1/findSickCircleList", {
            params: {
                departmentId: deptId,
                page: 1,
                count: 10,
            },
        }).then((res) => {
            setList(res.data.result || []);
        });
    };

    useEffect(() => {
        // 请求列表数据
        fetchList(listDeptId);
        // 取全部科室用于选择
        request.get("/share/knowledgeBase/v1/findDepartment").then((res) => {
            const arr = (res?.data?.result || []).map((d) => ({ label: d.departmentName, value: String(d.id) }));
            setDepartments(arr);
        })
    }, []);

    //   跳转详情页
    const handleItemClick = (id) => {
        navigate(`/circle/detail/${id}`);
    };

    // 点击发表打开弹框
    const handleOpenPublish = () => {
        setShowPublish(true);
    };

    // 表单提交
    const handleSubmit = async () => {
        const { title, departmentId, disease, detail } = form;
        if (!title || !departmentId || !disease || !detail) {
            Toast.show("请完整填写标题、科室ID、病症与详情");
            return;
        }
        try {
            const body = {
                ...form,
                departmentId: Number(form.departmentId),
                amount: Number(form.amount) || 0,
            };
            const res = await request.post(
                "/user/sickCircle/verify/v1/publishSickCircle",
                body,
                { headers: { "Content-Type": "application/json" }, transformRequest: [(data) => JSON.stringify(data)] }
            );
            if (res?.data?.status === "0000") {
                Toast.show("发表成功");
                setShowPublish(false);
                // 刷新列表：切换到所发科室
                const nextDept = Number(body.departmentId) || 1;
                setListDeptId(nextDept);
                fetchList(nextDept);
                // 乐观更新：将新内容插入列表顶部
                const optimistic = {
                    sickCircleId: res?.data?.result,
                    title: body.title,
                    detail: body.detail,
                    commentNum: 0,
                    releaseTime: '刚刚'
                };
                setList((prev) => [optimistic, ...prev]);
                setForm({
                    title: "",
                    departmentId: "",
                    departmentName: "",
                    disease: "",
                    detail: "",
                    treatmentHospital: "",
                    treatmentStartTime: "",
                    treatmentEndTime: "",
                    treatmentProcess: "",
                    amount: 0,
                });
            } else {
                Toast.show(res?.data?.message || "发表失败");
            }
        } catch (error) {
            console.error(error);
            Toast.show("发表失败，请重试");
        }
    };

    const filteredDiseaseOptions = (() => {
        if (!form.departmentId) return [];
        const list = diseaseMap[String(form.departmentId)];
        return list && list.length ? list : [];
    })();

    return (
        <div className={style.box}>
            <Navbar title={"康友圈"}></Navbar>
            <div className={style.addbtn} onClick={handleOpenPublish}>
                <AddOutline />
                <span className={style.text}>发表</span>
            </div>

            {/* 发表表单弹窗 - 顶部下拉抽屉 */}
            <Popup
                visible={showPublish}
                onMaskClick={() => setShowPublish(false)}
                onClose={() => setShowPublish(false)}
                position='top'
                style={{ "--z-index": 2000 }}
                maskStyle={{ background: "rgba(0,0,0,0.45)" }}
                bodyStyle={{ borderBottomLeftRadius: 12, borderBottomRightRadius: 12, height: '85vh', padding: 0, background: '#fff', overflow: 'hidden' }}
            >
                <div className={style.publishHeader} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: 16, background: '#f7fbff', borderBottom: '1px solid #eef3f8', color: '#1677ff' }}>
                    <div>发布病友圈</div>
                    <div onClick={() => setShowPublish(false)}>
                        <CloseOutline />
                    </div>
                </div>
                <div className={style.publishBody} style={{ padding: 16, paddingBottom: 72, maxHeight: 'calc(85vh - 120px)', overflow: 'auto' }}>
                    <div className={style.formItem}>
                        <div className={style.label}>标题</div>
                        <Input
                            placeholder="请输入标题"
                            value={form.title}
                            onChange={(val) => setForm((f) => ({ ...f, title: val }))}
                        />
                    </div>
                    <div className={style.formItem}>
                        <div className={style.label}>科室</div>
                        <div onClick={() => { setSelectorMode('dept'); setSelectorQuery(''); }} className={style.selectBox} style={{ color: form.departmentName ? '#333' : '#999' }}>
                            {form.departmentName || '请选择科室'}
                        </div>
                    </div>
                    <div className={style.formItem}>
                        <div className={style.label}>病症</div>
                        <div onClick={() => {
                            if (!form.departmentId) { Toast.show('请先选择科室'); return; }
                            // 若无缓存则触发加载
                            fetchDiseasesByDepartment(form.departmentId);
                            setSelectorMode('disease');
                            setSelectorQuery('');
                        }} className={style.selectBox} style={{ color: form.disease ? '#333' : '#999' }}>
                            {form.disease || '请选择病症（可选）'}
                        </div>
                    </div>
                    <div className={style.formItem}>
                        <div className={style.label}>详情</div>
                        <TextArea
                            placeholder="请输入详情"
                            value={form.detail}
                            rows={4}
                            onChange={(val) => setForm((f) => ({ ...f, detail: val }))}
                        />
                    </div>
                    <div className={style.formRow}>
                        <div className={style.formItemHalf}>
                            <div className={style.label}>医院</div>
                            <Input
                                placeholder="可选"
                                value={form.treatmentHospital}
                                onChange={(val) => setForm((f) => ({ ...f, treatmentHospital: val }))}
                            />
                        </div>
                        <div className={style.formItemHalf}>
                            <div className={style.label}>金额(元)</div>
                            <Input
                                placeholder="默认为0"
                                value={String(form.amount)}
                                onChange={(val) => setForm((f) => ({ ...f, amount: val }))}
                            />
                        </div>
                    </div>
                    <div className={style.formRow}>
                        <div className={style.formItemHalf}>
                            <div className={style.label}>开始时间</div>
                            <div onClick={() => setShowStartPicker(true)} className={style.selectBox} style={{ color: form.treatmentStartTime ? '#333' : '#999' }}>
                                {form.treatmentStartTime || '请选择开始时间'}
                            </div>
                        </div>
                        <div className={style.formItemHalf}>
                            <div className={style.label}>结束时间</div>
                            <div onClick={() => setShowEndPicker(true)} className={style.selectBox} style={{ color: form.treatmentEndTime ? '#333' : '#999' }}>
                                {form.treatmentEndTime || '请选择结束时间'}
                            </div>
                        </div>
                    </div>
                    <div className={style.formItem}>
                        <div className={style.label}>治疗过程</div>
                        <TextArea
                            placeholder="可选"
                            value={form.treatmentProcess}
                            rows={3}
                            onChange={(val) => setForm((f) => ({ ...f, treatmentProcess: val }))}
                        />
                    </div>
                </div>
                <div className={style.publishFooter} style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 16, background: '#fff', borderTop: '1px solid #f0f0f0' }}>
                    <Button color="primary" onClick={handleSubmit}>
                        提交
                    </Button>
                </div>
                {/* 内部选择面板（替代下拉框），避免层级问题 */}
                {selectorMode !== 'none' && (
                    <div className={style.selectorPanel}>
                        <div className={style.selectorHeader}>
                            <Button size='small' fill='none' color='primary' onClick={() => setSelectorMode('none')}>取消</Button>
                            <div className={style.selectorTitle}>{selectorMode === 'dept' ? '选择科室' : '选择病症'}</div>
                            <div style={{ width: 56 }} />
                        </div>
                        <div className={style.selectorSearchWrap}>
                            <Input placeholder='搜索关键词' value={selectorQuery} onChange={setSelectorQuery} />
                        </div>
                        <div className={style.selectorList}>
                            {(selectorMode === 'dept' ? departments : filteredDiseaseOptions)
                                .filter((opt) => (opt.label || opt).toString().includes(selectorQuery))
                                .map((opt) => (
                                    <div
                                        key={(opt.value || opt).toString()}
                                        className={style.selectorItem}
                                        onClick={() => {
                                            if (selectorMode === 'dept') {
                                                setForm((f) => ({ ...f, departmentId: opt.value, departmentName: opt.label, disease: '' }));
                                                // 选完科室后立即拉取对应病症
                                                fetchDiseasesByDepartment(opt.value);
                                            } else {
                                                setForm((f) => ({ ...f, disease: opt.label || opt }));
                                            }
                                            setSelectorMode('none');
                                        }}
                                    >
                                        {opt.label || opt}
                                    </div>
                                ))}
                        </div>
                    </div>
                )}
                {/* 内嵌日期选择器，放在抽屉内底部浮层，避免被遮挡 */}
                {showStartPicker && (
                    <div className={style.inlinePicker}>
                        <DatePickerView precision='day' value={parseDateFromString(form.treatmentStartTime) || startTempDate} onChange={setStartTempDate} />
                        <div className={style.inlineActions}>
                            <Button onClick={() => setShowStartPicker(false)}>取消</Button>
                            <Button color='primary' onClick={() => {
                                const d = startTempDate; const str = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`; setForm((f) => ({ ...f, treatmentStartTime: str })); setShowStartPicker(false);
                            }}>确定</Button>
                        </div>
                    </div>
                )}
                {showEndPicker && (
                    <div className={style.inlinePicker}>
                        <DatePickerView precision='day' value={parseDateFromString(form.treatmentEndTime) || endTempDate} onChange={setEndTempDate} />
                        <div className={style.inlineActions}>
                            <Button onClick={() => setShowEndPicker(false)}>取消</Button>
                            <Button color='primary' onClick={() => {
                                const d = endTempDate; const str = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`; setForm((f) => ({ ...f, treatmentEndTime: str })); setShowEndPicker(false);
                            }}>确定</Button>
                        </div>
                    </div>
                )}
            </Popup>

            {/* 列表 */}
            <div>
                {list.map((item, index) => {
                    return (
                        <div key={index} className={style.listbox} onClick={() => handleItemClick(item.sickCircleId)}>
                            <div className={style.listimg}>
                                <Avatar
                                    src="https://img.xz7.com/up/2019-3/20193201431191066.png"
                                    style={{ "--size": "48px" }}
                                />
                            </div>
                            <div className={style.listinner}>
                                <div className={style.listtitle}>
                                    <h4>
                                        康小友 | <span>官方号</span>
                                    </h4>
                                    <div className={style.time}>{item.releaseTime}回复</div>
                                </div>
                                <h4 className={style.wenzhangtitle}>{item.title}</h4>
                                <p className={style.wenzhanginner}>
                                    {item.detail}
                                    !感谢您的关注！为进一步做好新型冠状病毒感染医疗救治工作，提高疫情应对处置能力
                                </p>
                                <Button size="mini" color="primary" fill="outline">
                                    医生回答了该问题
                                </Button>
                                <br />
                                <div className={style.guancha}>
                                    <span>
                                        <EyeFill />
                                        370.2万
                                    </span>{" "}
                                    <span>
                                        <FillinOutline />
                                        {item.commentNum}条
                                    </span>
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}

export default Index;
